﻿using System;
using System.Linq;
using System.Threading;
using Hangfire;
using Hangfire.RecurringJobExtensions;
using Hangfire.Server;
using Microsoft.Extensions.DependencyInjection;
using SX.BaseService.Repository.Core;
using SX.BaseService.Repository.Entity;
using SX.Core.HangFire;

namespace SX.BaseService.API
{
	[AutomaticRetry(Attempts = 0)]
	[DisableConcurrentExecution(90)]
	public class LongRunningJob :DbContext,IRecurringJob
	{
        private static bool IsRunning;
        private static object _obj = new object();

        public void Execute(PerformContext context)
        {
            if (IsRunning == false)
            {
                lock (_obj)
                {
                    if (IsRunning == false)
                    {
                        IsRunning = true;
                        Console.WriteLine("开始执行缓存更新任务");
                        try
                        {
                            context.GetJobData();
                            using (var scope = HangfireServiceProvider.ServiceProvider.CreateScope())
                            {
                               //这里写具体的操作
                                
                            }
                            Console.WriteLine("结束执行缓存更新任务");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"执行缓存更新任务出现异常:{ex}");
                        }
                        IsRunning = false;
                    }
                }
            }
        }
    }
}
